package cn.sangyy.basic.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度认证工具类：注意要修改API Key 和 Secret Key
 */
public class BaiduAuditUtils {
    /**
     * 获取权限token
     * @return 返回示例：
     * {
     * "access_token": "24.3265383f84ac64db9eff781e70587614.2592000.1654844607.282335-26205415",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "BaMgVdlLVS0CHnfSVCMLbBNK";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "kQuq8WirwwMBALKYSeQPIHU8DHHYGCiv";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
           /* for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            //System.err.println("result:" + result);
            JSONObject jsonObject= JSONObject.parseObject(result);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            //System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 文本审核
     * @param param
     * @return
     */
    public static Map<String,Object> textCensor(String param) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();
			//处理参数格式
            param = "text=" + param;

            return getStringObjectMap(param, url, accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Map<String, Object> getStringObjectMap(String param, String url, String accessToken) throws Exception {
        String result = HttpUtil.post(url, accessToken, param);
        JSONObject jsonObject= JSONObject.parseObject(result);
        String conclusion = jsonObject.getString("conclusion");
        Map<String,Object> map =  new HashMap<>();
        if ("合规".equals(conclusion)){
            map.put("success",true);
            map.put("message","合规");
        }else {
            String dataStr =  jsonObject.getString("data");
            JSONArray jsonArray = JSONObject.parseArray(dataStr);
            String errorMsg= jsonArray.getJSONObject(0).getString("msg");
            map.put("success",false);
            map.put("message",errorMsg);
        }
        return map;
    }

    /**
     * @param imageUrl 需要审核的图片路径地址
     * @return
     */
    public static Map<String, Object> imgCensor(String imageUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            URL httpUrl = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] imgData = readInputStream(inStream);//得到图片的二进制数据
            //图片地址进行编码
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//            imgParam=imgParam.replaceAll("=", "%3D").replaceAll("\\+","%2B");
            //设置参数
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();
            return getStringObjectMap(param, url, accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> censor(String content,String imageUrl) {
        String errorMsg = "";
        //审核文本
        if(StringUtils.isNotBlank(content)){
            //调用文本审核方法
            Map<String, Object> map1 = textCensor(content);
            Boolean success = (Boolean)map1.get("success");
            if(!success){
                errorMsg += content+"审核不通过，不通过原因:"+map1.get("message").toString();
            }
        }
        //审核图片
        if(StringUtils.isNotBlank(imageUrl)){
            String[] images = imageUrl.split(",");
            for (String image : images) {
                //调用图片审核方法
                Map<String, Object> map2 = imgCensor(image);
                Boolean success = (Boolean)map2.get("success");
                if(!success){
                    errorMsg += "图片"+"<img src='"+image+"'style='width:50px;height:50px;'/>"
                            +"审核不通过，不通过原因:"+map2.get("message").toString();
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isBlank(errorMsg)){
            map.put("success",true);
            map.put("message","审核通过！");
        }else {
            map.put("success",false);
            map.put("message",errorMsg);
        }
        return map;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static void main(String[] args) {
        System.out.println(BaiduAuditUtils.getAuth());
        //System.out.println("姚桑:"+BaiduAuditUtils.textCensor("姚桑"));//false
        //System.out.println(BaiduAuditUtils.textCensor("cnm"));//false
        System.out.println(BaiduAuditUtils.textCensor("宝马x3系列，高端大气上档次，开展舒适放心。sb"));//false
        //System.out.println(BaiduAuditUtils.textCensor("牛逼"));//true
        //System.out.println(BaiduAuditUtils.textCensor("日寇"));//true
//        System.out.println(BaiduAuditUtils.textCensor("小黑子"));//true
//        System.out.println(BaiduAuditUtils.imgCensor("https://sangyy-gift-1312587115.cos.ap-chengdu.myqcloud.com/images/rcb/779f3fd9-ac22-4de0-91cb-33cac4b3aa37_head1.jpeg"));//true
//        System.out.println(BaiduAuditUtils.imgCensor("https://sangyy-gift-1312587115.cos.ap-chengdu.myqcloud.com/images/rcb/68cc742c-179d-4162-adaf-9f859a1f7465_0001.jpeg"));
    }

}